using System.Collections.Generic;
using System.Linq;
using Roslyn.Compilers.CSharp;

namespace Roslyn.Refactoring.Library
{
    class ExtractParameterRewriter : SyntaxRewriter
    {
        public MethodDeclarationSyntax DeclarationNode;
        public ExpressionSyntax ExpressionNode;
        public string NewType;
        public string VariableName;

        protected override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            if(node != DeclarationNode)
                return base.VisitMethodDeclaration(node);
            node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
            
            
            var newParameter = Syntax.Parameter(identifier: Syntax.Identifier(" " + VariableName), typeOpt: Syntax.ParseTypeName(NewType));
            var paramsList = new List<ParameterSyntax>(node.ParameterList.Parameters) {newParameter};
            var argSeparators = Enumerable.Repeat(Syntax.Token(SyntaxKind.CommaToken), paramsList.Count - 1).ToList();
  
            var separatedSyntaxList = Syntax.SeparatedList<ParameterSyntax>(paramsList, argSeparators);
            var newParams = node.ParameterList.Update(node.ParameterList.OpenParenToken,
                                                      separatedSyntaxList,
                                                      node.ParameterList.CloseParenToken
                );

            return node.Update(
                node.Attributes, node.Modifiers, node.ReturnType, node.ExplicitInterfaceSpecifierOpt, node.Identifier,
                node.TypeParameterListOpt, newParams, node.ConstraintClauses, node.BodyOpt,
                node.SemicolonTokenOpt);
        }
        public override SyntaxNode Visit(SyntaxNode node)
        {
            if (node != ExpressionNode)
                return base.Visit(node);
            return Syntax.IdentifierName(VariableName);
        }
    }
}